package com.lalilu.lmedia.database

import androidx.room.*
import com.lalilu.lmedia.entity.LPlaylist
import kotlinx.coroutines.flow.Flow

@Dao
abstract class PlaylistDao : LinkableDao<LPlaylist>() {

    @Insert(entity = LPlaylist::class, onConflict = OnConflictStrategy.REPLACE)
    abstract override fun insert(item: LPlaylist): Long

    @Insert(entity = LPlaylist::class, onConflict = OnConflictStrategy.REPLACE)
    abstract override fun insertAll(items: List<LPlaylist>)

    @Delete(entity = LPlaylist::class)
    abstract override fun remove(item: LPlaylist)

    @Query("SELECT * FROM playlist WHERE p_id = :id OR :classifyId LIMIT 1;")
    abstract override fun getById(id: Long, classifyId: Long?): LPlaylist?

    @Query("SELECT * FROM playlist WHERE nextId = :nextId OR :classifyId LIMIT 1;")
    abstract override fun getByNextId(nextId: Long, classifyId: Long?): LPlaylist?

    @Query("SELECT * FROM playlist WHERE nextId IS NULL OR :classifyId LIMIT 1 ")
    abstract override fun getLastOne(classifyId: Long?): LPlaylist?

    @Query("SELECT * FROM playlist ORDER BY p_id DESC LIMIT 1;")
    abstract override fun getLastOne(): LPlaylist?

    @Update(entity = LPlaylist::class)
    abstract override fun update(item: LPlaylist)

    @Transaction
    @Update(entity = LPlaylist::class)
    abstract override fun updateAll(items: List<LPlaylist>)

    @Query("SELECT * FROM playlist;")
    abstract fun getAllFlow(): Flow<List<LPlaylist>>

    @MapInfo(keyColumn = "pId", valueColumn = "sId")
    @Query("SELECT playlist.p_id AS pId, s_id AS sId from playlist JOIN song_in_playlist ON playlist.p_id = song_in_playlist.p_id;")
    abstract fun getAllDetailByIdFlow(): Flow<Map<Long, List<String>>>

    @Query("SELECT * FROM playlist WHERE p_id = :id;")
    abstract fun getById(id: String): LPlaylist?

    @Query("SELECT * FROM playlist WHERE p_id = :id;")
    abstract fun getFlowById(id: Long): Flow<LPlaylist>
}